package com.chuanyang.driverh.mainorder;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.mainorder.adapter.OrderInfoAdapter;
import com.chuanyang.driverh.mainorder.adapter.OrderPassPointAdapter;
import com.chuanyang.driverh.responseresult.DriverInfoData;
import com.chuanyang.driverh.responseresult.OrderDatailResult;
import com.chuanyang.driverh.responseresult.OrderDetailData;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.utils.ActivityUtil;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.TimeUtils;
import com.chuanyang.driverh.utils.eventbus.RemoveEvent;
import com.chuanyang.driverh.utils.eventbus.SubscribeEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;
import com.chuanyang.driverh.utils.widget.CustomMeasureHeightListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

public class NewPendHisOrderDetailActivity extends BaseTitleActivity {
    public int index = 0;
    private ImageView iv_peopleicon;
    private RatingBar ratingBar;
    private TextView tv_peoplename;
    private TextView tv_phone;
    private TextView tv_orderdate;
    private TextView tv_oredrinfo_deliverydate;
    private TextView tv_oredrinfo_picuupdate;
    private TextView tv_oredrinfodetail_orderid;
    private TextView tv_oredrinfo_act;
    private CustomMeasureHeightListView lv_varpalaces;
    private CustomMeasureHeightListView lv_orderlist;
    private HashMap params;
    private ScrollView sc_orderdetail;
    private OrderDetailData.PassPointsBean startPoint;
    private OrderDetailData.PassPointsBean endPoint;
    private List<OrderDetailData.PassPointsBean> fillpointlist;
    private OrderPassPointAdapter passPointAdapter;
    private List<OrderDetailData.PassPointsBean> passpointlist;
    private LinearLayout ll_oredrinfo_goodownerdiv;
    private TextView tv_oredrinfo_dingyue;
    private String orderId;
    private OrderDetailData orderDetail;
    private LinearLayout ll_oredrinfo_act;
    private TextView tv_oredrinfo_act2;
    private TextView tv_oredrinfo_remark;
    private ImageView iv_oredrinfo_phoneicon;
    private DriverInfoData driverinfo;
    private OrderDetailData pushOrder;
    private String ordertype;//        //"1"表示搁置的待处理订单 "2"表示普通的待处理订单  "3"表示订单历史
    private Intent intent;
    private TextView tv_oredrinfodetail_tradetype;
    private TextView tv_oredrinfodetail_taskname;
    private TextView tv_oredrinfodetail_realnum;
    private TextView tv_oredrinfodetail_orginnum;
    private TextView tv_oredrinfodetail_realweight;
    private TextView tv_oredrinfodetail_orginweight;
    private TextView tv_oredrinfodetail_realamount;
    private TextView tv_oredrinfodetail_orginamount;
    private LinearLayout ll_orderinfo_cartimediv;
    private LinearLayout ll_orderinfo_shiptimediv;
    private TextView tv_driverinfo_loaddatebeg;
    private TextView tv_driverinfo_loaddateend;
    private TextView tv_driverinfo_stevedoreDaybeg;
    private TextView tv_driverinfo_stevedoreDayend;
    private TextView tv_oredrinfodetail_demurrage;

    private Dialog dialog;

    @Override
    protected int getContentResId() {
        return R.layout.order_act_newpendhisorderdetailinfo;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        showActivityLoading();
        ll_oredrinfo_goodownerdiv = (LinearLayout) findViewById(R.id.ll_oredrinfo_goodownerdiv);
        sc_orderdetail = (ScrollView) findViewById(R.id.sc_orderdetail);
        iv_peopleicon = (ImageView) findViewById(R.id.iv_oredrinfo_peopleicon);
        ratingBar = (RatingBar) findViewById(R.id.rb_orderinfo_stars);
        tv_peoplename = (TextView) findViewById(R.id.tv_oredrinfo_peoplename);
        tv_oredrinfo_dingyue = (TextView) findViewById(R.id.tv_oredrinfo_dingyue);//订阅
        tv_phone = (TextView) findViewById(R.id.tv_oredrinfo_phone);
        iv_oredrinfo_phoneicon = (ImageView) findViewById(R.id.iv_oredrinfo_phoneicon);
        tv_orderdate = (TextView) findViewById(R.id.tv_oredrinfo_orderdate);//发单时间
        //车辆订单时显示的界面
        ll_orderinfo_cartimediv = (LinearLayout) findViewById(R.id.ll_orderinfo_cartimediv);
        tv_oredrinfo_deliverydate = (TextView) findViewById(R.id.tv_oredrinfo_deliverydate);//发货时间
        tv_oredrinfo_picuupdate = (TextView) findViewById(R.id.tv_oredrinfo_picuupdate);//取货时间

        //-----------------------

        //船只订单时显示的界面
        ll_orderinfo_shiptimediv = (LinearLayout) findViewById(R.id.ll_orderinfo_shiptimediv);
        tv_driverinfo_loaddatebeg = (TextView) findViewById(R.id.tv_driverinfo_loaddatebeg);
        tv_driverinfo_loaddateend = (TextView) findViewById(R.id.tv_driverinfo_loaddateend);
        tv_driverinfo_stevedoreDaybeg = (TextView) findViewById(R.id.tv_driverinfo_stevedoreDaybeg);
        tv_driverinfo_stevedoreDayend = (TextView) findViewById(R.id.tv_driverinfo_stevedoreDayend);
        //滞期费
        tv_oredrinfodetail_demurrage = (TextView) findViewById(R.id.tv_oredrinfodetail_demurrage);

        //-----------------------

        tv_oredrinfo_remark = (TextView) findViewById(R.id.tv_oredrinfo_remark);
        tv_oredrinfodetail_orderid = (TextView) findViewById(R.id.tv_oredrinfodetail_orderid);//订单号

        //实际数量
        tv_oredrinfodetail_realnum = (TextView) findViewById(R.id.tv_oredrinfodetail_realnum);
        //下单数量
        tv_oredrinfodetail_orginnum = (TextView) findViewById(R.id.tv_oredrinfodetail_orginnum);

        //实际载重
        tv_oredrinfodetail_realweight = (TextView) findViewById(R.id.tv_oredrinfodetail_realweight);
        //下单载重
        tv_oredrinfodetail_orginweight = (TextView) findViewById(R.id.tv_oredrinfodetail_orginweight);
        //实际金额
        tv_oredrinfodetail_realamount = (TextView) findViewById(R.id.tv_oredrinfodetail_realamount);
        //下单金额
        tv_oredrinfodetail_orginamount = (TextView) findViewById(R.id.tv_oredrinfodetail_orginamount);
        //任务名称
        tv_oredrinfodetail_taskname = (TextView) findViewById(R.id.tv_oredrinfodetail_taskname);
        tv_oredrinfodetail_tradetype = (TextView) findViewById(R.id.tv_oredrinfodetail_tradetype);//订单外贸类型（1人民币，2美元）
        tv_oredrinfodetail_taskname = (TextView) findViewById(R.id.tv_oredrinfodetail_taskname);//任务名称

        ll_oredrinfo_act = (LinearLayout) findViewById(R.id.ll_oredrinfo_act);        //底部两个按钮所在布局
        tv_oredrinfo_act = (TextView) findViewById(R.id.tv_oredrinfo_act);//最底部的按钮1
        tv_oredrinfo_act2 = (TextView) findViewById(R.id.tv_oredrinfo_act2);//最底部的按钮2
        lv_varpalaces = (CustomMeasureHeightListView) findViewById(R.id.ll_oredrinfo_varpalace);
        lv_orderlist = (CustomMeasureHeightListView) findViewById(R.id.ll_orderinfo_orderlist);


    }

    @Override
    protected void initData() {
        intent = getIntent();
        orderId = intent.getStringExtra("OrderId");
        //"1"表示搁置的待处理订单 "2"表示普通的待处理订单  "3"表示订单历史
        ordertype = intent.getStringExtra("index");
        setBackImg();
        if (ordertype.equals("1") || ordertype.equals("2")) {
            getTitleTextView().setText("待处理订单");

        } else {
            getTitleTextView().setText("历史订单");
        }

//        driverinfo = (DriverInfoData) PreferencesUtil.getPreferences(this, "DriverInfoData");
        //获取存入的最新一个推送来的订单
        if (SharedPrefUtil.getPreferences("SheveOrder",new OrderDetailData()) != null && ordertype.equals("1")) { //代表是搁置的待处理订单
            pushOrder = (OrderDetailData) SharedPrefUtil.getPreferences("SheveOrder",new OrderDetailData());
            fillView(pushOrder);
        } else {
            requsetData();
        }

    }

    @Override
    protected void initListener() {
        ll_oredrinfo_goodownerdiv.setOnClickListener(this);
        tv_oredrinfo_act.setOnClickListener(this);
        tv_oredrinfo_act2.setOnClickListener(this);
        iv_oredrinfo_phoneicon.setOnClickListener(this);

    }



    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_oredrinfo_goodownerdiv:
                if (orderDetail != null) {
                    ActivityUtil.startActivity(activityContext,new Intent(activityContext,GoodOwnerInfoActivity.class).putExtra("data",orderDetail));
                }
                break;
            case R.id.tv_oredrinfo_act:
                if (ordertype.equals("1")) {
                    receiveOrder(pushOrder, 0);
                } else {
                    receiveOrder(orderDetail, 1);
                }
                break;
            case R.id.tv_oredrinfo_act2:
                if (ordertype.equals("1")) {
                    adandonOrder(pushOrder);
                } else {
                    adandonOrder(orderDetail);
                }
                break;
            case R.id.iv_oredrinfo_phoneicon:
                if (orderDetail.getPhone() != null) {
                    dial(orderDetail.getPhone());
                }
                break;
        }
    }

    private void dial(final String tel){
        dialog= DialogUtil.myDialog(activityContext, "拨打电话", "取消", "确定","确定拨打："+tel+"?", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.dialog_btn_left:
                        break;
                    case R.id.dialog_btn_right:
                        DialogUtil.dial(activityContext,tel);
                       /* Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tel));
                        try {
                            if (PermissoinUtil.checkAndRequestPermission(activityContext, android.Manifest.permission.CALL_PHONE, "请给应用添加拨打电话的权限！"))
                                startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }*/
                        break;
                }
                dialog.cancel();
            }
        });
    }

    private void requsetData() {
        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderId", orderId);
        MyHttpUtil.selectOrderMsgById(activityContext,params, new MyCallback<OrderDatailResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(OrderDatailResult result, int id) {

                if (result.getCode() == ConstUtil.OK ) {
                    orderDetail = result.getData();
                    fillView(orderDetail);
                    hideActivityLoading();
                }
            }
        });


    }


    /**
     * 如果订阅信息有变化时，需要修改其订阅按钮的状态
     *
     * @param event
     */
    public void onEventMainThread(SubscribeEvent event) {
        if (event.isChangeSubscribed()) {
            requsetData();
        }

    }

    private void fillView(OrderDetailData data) {
        BitmapUtil.showImgForNetPath(data.getUserImage(),iv_peopleicon);
        if (data.getStar() != 0) {
            ratingBar.setRating(data.getStar());
        }
        tv_phone.setText(data.getPhone());
        if (!TextUtils.isEmpty(data.getRemark())) {
            tv_oredrinfo_remark.setText(data.getRemark());
        } else {
            tv_oredrinfo_remark.setText("");

        }

        tv_orderdate.setText(TimeUtils.getStandardTime(data.getOrder_time()));
        passpointlist = new ArrayList();
        tv_oredrinfodetail_orderid.setText(data.getOrderNo());

        if (!TextUtils.isEmpty(data.getAssignment())) {
            tv_oredrinfodetail_taskname.setText("任务名称：" + data.getAssignment());
        } else {
            tv_oredrinfodetail_taskname.setVisibility(View.GONE);
        }
        if (data.getCurrency() == 2) //2为外贸
        {
            tv_oredrinfodetail_tradetype.setVisibility(View.VISIBLE);
        } else {
            tv_oredrinfodetail_tradetype.setText("内贸");
        }

        if (orderDetail.getGoodsSum() != null) {
            tv_oredrinfodetail_orginweight.setText("下单重量："+orderDetail.getGoodsSumWeight()+"t");
            tv_oredrinfodetail_orginnum.setText("下单数量："+orderDetail.getGoodsSumNum());
            double orginamount = (orderDetail.getGoodsSum().getGoodsWeight()) * (orderDetail.getPrice());
            tv_oredrinfodetail_orginamount.setText("下单金额："+String.format("%.2f", orginamount) + orderDetail.getUnit());
        }
        else {
            tv_oredrinfodetail_orginamount.setVisibility(View.GONE);
            tv_oredrinfodetail_orginamount.setVisibility(View.GONE);
            tv_oredrinfodetail_orginamount.setVisibility(View.GONE);

        }
        if(orderDetail.getRealitySum()!=null)
        {
            tv_oredrinfodetail_realnum.setText("实际数量："+orderDetail.getRealitySum().getRealityNum());
            tv_oredrinfodetail_realweight.setText("实际重量： "+orderDetail.getRealitySum().getRealityWeight()+"t");
            double realamount=(orderDetail.getRealitySum().getRealityWeight())*orderDetail.getPrice();
            tv_oredrinfodetail_realamount.setText("实际金额： "+String.format("%.2f", realamount)+data.getUnit());
        }
        else {
            tv_oredrinfodetail_realnum.setVisibility(View.GONE);
            tv_oredrinfodetail_realweight.setVisibility(View.GONE);
            tv_oredrinfodetail_realamount.setVisibility(View.GONE);
        }
        if (data.getTransPortWay() == 1)//车
        {
            tv_oredrinfo_deliverydate.setText(TimeUtils.getStandardTime(data.getOrder_startime()));
            tv_oredrinfo_picuupdate.setText(TimeUtils.getStandardTime(data.getOrder_endtime()));
            ll_orderinfo_cartimediv.setVisibility(View.VISIBLE);
            ll_orderinfo_shiptimediv.setVisibility(View.GONE);

        } else if (data.getTransPortWay() == 2)//船
        {
            tv_driverinfo_loaddatebeg.setText(data.getLoadDate());
            tv_driverinfo_loaddateend.setText(TimeUtils.getStandardTime(data.getOrder_endtime()));
            tv_driverinfo_stevedoreDaybeg.setText(data.getStevedoreDay());
            tv_driverinfo_stevedoreDayend.setText(data.getFq());
            tv_oredrinfodetail_demurrage.setText(data.getDemurrage()+data.getUnit()+"/天/吨");
            ll_orderinfo_cartimediv.setVisibility(View.GONE);
            ll_orderinfo_shiptimediv.setVisibility(View.VISIBLE);

        }
        if (data.getUsername() != null) {
            tv_peoplename.setText(data.getUsername());

        } else {
            tv_peoplename.setText("---");

        }
        if (data.getSubscriptionStatus() == 1) {
            tv_oredrinfo_dingyue.setText("已订阅");
        } else if (data.getSubscriptionStatus() == 2) {
            tv_oredrinfo_dingyue.setText("未订阅");
        }
        //需要传入到适配器的数据
        fillpointlist = new ArrayList();
        for (OrderDetailData.PassPointsBean passPointsBean : data.getPassPoints()) {
            if (passPointsBean.getPointType().equals("s")) {
                startPoint = passPointsBean;
            } else if (passPointsBean.getPointType().equals("p")) {
                passpointlist.add(passPointsBean);
            } else {
                endPoint = passPointsBean;

            }
        }
        OrderInfoAdapter orderInfoAdapter = new OrderInfoAdapter(this, data.getDetailList());
        lv_orderlist.setAdapter(orderInfoAdapter);
        fillpointlist.clear();
        fillpointlist.add(startPoint);
        lv_varpalaces.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (passpointlist.size() > 0) {
                    if (0 < position && position < passpointlist.size() + 1) {
                        fillpointlist.clear();
                        fillpointlist.add(startPoint);
                        if ((index++) % 2 == 1) {
                            fillpointlist.addAll(passpointlist);
                            fillpointlist.add(endPoint);

                        } else {
                            fillpointlist.add(passpointlist.get(0));
                            fillpointlist.add(endPoint);

                        }

                        passPointAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
        if (passpointlist.size() > 0) {
            fillpointlist.add(passpointlist.get(0));


        }
        fillpointlist.add(endPoint);
        passPointAdapter = new OrderPassPointAdapter(this, fillpointlist);
        //设置数据适配器
        lv_varpalaces.setAdapter(passPointAdapter);
        if (data.getOrder_status() < 0) {

            ll_oredrinfo_act.setVisibility(View.GONE);

        }
        if (data.getOrder_status() == 0) {//刚刚初始化的订单

            ll_oredrinfo_act.setVisibility(View.GONE);

        }
        if (ordertype.equals("3")) {
            ll_oredrinfo_act.setVisibility(View.GONE);

        } else {
            if (pushOrder != null) {
                tv_oredrinfo_act.setText("接受");
                tv_oredrinfo_act2.setText("放弃");

            } else {
                if (data.getOrder_type() == 3)//司机可能没收到推送 此时待处理专线单可以接受
                {
                    tv_oredrinfo_act.setText("接受");
                    tv_oredrinfo_act2.setVisibility(View.GONE);
                } else {
                    tv_oredrinfo_act.setVisibility(View.GONE);
                    tv_oredrinfo_act2.setText("放弃");
                }


            }
            ll_oredrinfo_act.setVisibility(View.VISIBLE);

        }


        //滚动到原点  注意这两个方法需要一起使用 前者打断动画，后者实现移动
        sc_orderdetail.scrollTo(0, 0);
        sc_orderdetail.smoothScrollTo(0, 0);
    }


    /**
     * 接单操作      (不是推送来的专线订单，而是列表里的专线订单 接收时传“1”)
     */
    private void receiveOrder(final OrderDetailData order, int i) {
        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("orderId", order.getOrderId() + "");
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderType", order.getOrder_type() + "");//订单类型
        if (i == 1) {
            params.put("appoint", "1");
            params.put("type", intent.getStringExtra("type"));
        }
        else {
            if (!TextUtils.isEmpty(order.getAppoint())) {
                params.put("appoint", order.getAppoint());
            }
            params.put("type", order.getType() + "");
        }
        MyHttpUtil.receiveOrder(activityContext,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(Result result, int id) {

                if (result.getCode() == ConstUtil.OK ) {
                   PrintUtil.toast(NewPendHisOrderDetailActivity.this, "接单成功");
                    Intent intent = new Intent(NewPendHisOrderDetailActivity.this, MatchOrderResultActivity.class);
                    intent.putExtra("orderNum", order.getOrderNo());
                    intent.putExtra("orderId", order.getOrderId() + "");
                    intent.putExtra("opreateType", "2");
                    startActivity(intent);
                    EventBus.getDefault().post(new RemoveEvent(true));
                    finish();
                } else {
                    PrintUtil.toast(activityContext,"您接单失败");
                }
            }
        });

    }

    /**
     * 放弃待处理订单
     */
    public void adandonOrder(final OrderDetailData order) {
        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("orderId", order.getOrderId() + "");
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("type", order.getOrder_type() + "");
        MyHttpUtil.deletePendOrder(activityContext,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(Result result, int id) {

                if (result.getCode() == ConstUtil.OK ) {
                    if (ordertype.equals("1")) {
                        EventBus.getDefault().post(new RemoveEvent(true));
                        PrintUtil.toast(activityContext,"您已放弃该订单");
                    } else {
                        EventBus.getDefault().post(new RemoveEvent(false));

                    }
                    onBackPressed();
                }
            }
        });


    }
}
